# import pathlib
# import importlib.util
# import sys
import os
import configs
import importlib
import json
import sys
from configs import languages
from template.singleton import Singleton
from utils import service_functions

error = {}


class Import_egg(Singleton):
    def __init__(self):
        # sys.path.append(f"{configs.path_core}/api.py")
        # print(sys.path)
        self.settings()

    def settings(self):
        # self.import_dict["Import_egg_update"] = {"id": self.__update,"blocking": configs.blocking_update_flag}
        self.import_dict = {}
        self.list_update = []
        self.menu = "import"
        self.error_import = {}
        self.key = ""
        self.read_dir()

    def cheek_update(self, link):
        pass

    def read_dir(self):
        list_egg_dir = os.listdir(configs.way_egg)
        for egg in list_egg_dir:
            try:
                path_egg = configs.way_egg + egg
                egg_files = os.listdir(path_egg)
                # print(egg_files)
                if "configs.json" in egg_files:
                    config_modul = self.__read_config(f"{path_egg}/configs.json")
                    # print(config_modul)
                    if len(config_modul) != 0:
                        if self.menu == "import":
                            self.import_main_file(config_modul, path_egg)
                        elif self.menu == "update":
                            pass
                            # self.__update(config_modul,path_egg)
                        else:
                            continue
                    else:
                        continue
                else:
                    continue
            except Exception as e:
                # print("жопа 218")
                print(e)
                # obj_configs.communication_obj.messege("Моудь упал")

    def set_list_update(self, list_update):
        self.list_update = list_update

    def add_global_config(self, config_modul):
        for key, values_conf in configs.cmds["void"].items():
            for key_egg, values_egg in config_modul["void"].items():
                for value in values_egg["word_list"]:
                    if (value in values_conf) or (key == key_egg):
                        if not (key_egg in self.error_import):
                            self.error_import[key_egg] = config_modul["name"]
                    else:
                        configs.cmds["void"] = dict(
                            list(configs.cmds["void"].items())
                            + list(config_modul["void"].items())
                        )
                        # print(configs.cmds["void"])
        # print(self.cheek_update("https://github.com/kaldi-asr/ka"))
        configs.cmds_void = configs.cmds["void"]

    def __update(self, config_modul, path_egg) -> None:
        # Дописать
        name_modul = config_modul["name"]
        if name_modul in self.list_update or len(self.list_update) == 0:
            class_name = config_modul["class_name"]
            list_methods_public = config_modul["method_public"]
            # link = config_modul["link"]
            # version = config_modul["version"]
            self.sys_path_main(path_egg)
            for func_str in list_methods_public:
                self.import_dict[f"{class_name}_{func_str}"]["blocking"] = True
            for func_str in list_methods_public:
                self.import_dict[f"{class_name}_{func_str}"]["blocking"] = False

    def sys_path_main(self, path_main_file_egg) -> None:
        if sys.path.count(path_main_file_egg) == 0:
            sys.path.append(path_main_file_egg)
        else:
            pass
            # self.cheek_update(path_main_file_egg)

    def import_module_from_spec(self, module_spec):
        module = importlib.util.module_from_spec(module_spec)
        module_spec.loader.exec_module(module)
        # print("\n\n\n\n\n\n\n\n",module,"\n\n\n\n\n\n\n\n")
        return module

    def __read_config(self, file_name):
        with open(file_name) as f:
            try:
                return json.load(f)
            except BaseException:
                return {}

    def error(self, *args, **kwargs) -> str:
        return languages["import_funcs"]["egg"]["mess"]

    def keys(self, key: str) -> None:
        # print("жопа 223")
        old_label_not = key.find("_")
        if old_label_not != -1:
            self.key = key[old_label_not + 1 : len(key)]
        self.key = key

    def import_func(self):
        try:
            id_func = self.import_dict[self.key]["id"]
            # print(id_func)
            return id_func
        except BaseException:
            if not (self.key in self.import_dict):
                self.import_dict[self.key]["blocking"] = True
                error_import = f"Модуле {self.key} была произвендена блокировка по причине его утсуствия"
                service_functions.write_meta_data(error_import, "error.txt")
            return self.error

    def import_main_file(self, config_modul, path_egg):
        name_modul = config_modul["name"]
        class_name = config_modul["class_name"]
        list_methods_public = config_modul["method_public"]
        self.sys_path_main(path_egg)
        file1 = importlib.import_module(name_modul)
        # print(file1,2222222222222222222222222222222222222222222)
        class_id = getattr(file1, class_name)
        # print(class_id,"\n\n\n\n\n\n\n\n")
        class_exute = class_id()
        for func_str in list_methods_public:
            func_id = getattr(class_exute, func_str)
            # print("\n\n\n\n\n\n\n\n22222222222",func_id,"\n\n\n\n\n\n\n\n222222222")
            if self.settings_egg(class_id, config_modul):
                if not (func_str in self.import_dict):
                    self.import_dict[f"{class_name}_{func_str}"] = {
                        "id": func_id,
                        "blocking": False,
                    }
                    self.add_global_config(config_modul)
                else:
                    # link = config_modul["link"]
                    # version = config_modul["version"]
                    # self.update(link,version)
                    # Я не форточник !!!

                    # obj_configs.service_functions.util_command_history_write(f"{class_name}_{func_str}","error.txt")
                    pass
        # print(self.import_dict)

    def settings_egg(self, class_id, config_modul):
        list_lang = config_modul["list_language"]
        if configs.languages in list_lang:
            class_exute = class_id()
            # class_exute.local_settings(config_modul["settings"])
            class_exute.set_language(configs.languages)
            class_exute.config(configs.cmds_void)
            class_exute.settings(configs.settings)
            # class_exute.set_obj_kernel(obj_configs.dict_class)
            return True
        else:
            return False


class Import_core_apps(Singleton):
    def __init__(self) -> None:
        self.name_func = ""

    def class_name(self, name):
        self.name = name

    def keys(self, name_func):
        # print(name_func)
        old_label_not = name_func.find("__")
        self.name_func = name_func.replace(" ", "")
        self.name_func = name_func.replace("\n", "")
        if old_label_not != -1:
            self.name_func = name_func[0:old_label_not]
            # print(self.name_func,222222)
        # print(bytes(self.name_func,encoding='utf-8'),111111)
        # self.name_func = name_func
        # print(self.name_func,111)

    def __error(self, *args, **kwargs):
        return languages["import_funcs"]["apps"]["mess"]

    def import_func(self):
        if len(self.name_func) != 0:
            name_func = self.name_func
            self.name_func = ""
            if hasattr(self.name, name_func):
                try:
                    return getattr(self.name, name_func)
                except BaseException:
                    print("жопа 1")
                    return self.__error
            else:
                print("жопа 2")
                return self.__error
        else:
            print("жопа 3")
            return self.__error


class Web_app:
    def __init__(self) -> None:
        self.settings()

    def settings(self):
        pass


"""
obj = Import_func()

for x in range(3):

    obj.keys('Weather.Weather.api_get_str')
    # obj.import_func()
    print(obj.import_func()())
    obj.keys('Time_module.Time_module.api_get_time_clock')
    # obj.import_func()
    print(obj.import_func()())

"""
